import shutil
from pathlib import Path
from datetime import datetime
import requests
from PIL import Image
from requests_toolbelt.multipart.encoder import MultipartEncoder

class EventUploader:
    def __init__(self):
        self.key_frames = [0, 3, 7]  # 对应第1,4,8张图片

    def generate_events(self, source_dir: str, output_dir: str):
        """生成事件包（GIF+关键帧）"""
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        
        # 获取并排序源图片
        images = sorted(
            Path(source_dir).glob("*.jpg"),
            key=lambda x: int(x.stem.split('_')[-1])
        )

        for batch_idx in range(0, len(images), 8):
            batch = images[batch_idx:batch_idx+8]
            if len(batch) < 8:
                continue  # 跳过不足8张的批次

            # 创建事件目录
            event_id = f"event_{batch_idx//8:03d}"
            event_dir = Path(output_dir) / event_id
            event_dir.mkdir(exist_ok=True)

            # 保存关键帧
            key_files = []
            for idx in self.key_frames:
                src = batch[idx]
                dest = event_dir / f"key_{idx+1}.jpg"  # key_1.jpg, key_4.jpg, key_8.jpg
                shutil.copy(src, dest)
                key_files.append(dest)

            # 生成GIF
            gif_path = event_dir / f"{event_id}.gif"
            self._create_gif(batch, gif_path)

            # 记录时间戳
            (event_dir / "timestamp").write_text(datetime.now().isoformat())

    def _create_gif(self, images: list, output_path: Path):
        """生成GIF文件"""
        frames = []
        for img_path in images:
            with Image.open(img_path) as img:
                frames.append(img.resize((img.width//4, img.height//4)))
        
        frames[0].save(
            output_path,
            save_all=True,
            append_images=frames[1:],
            duration=200,
            loop=0,
            optimize=True
        )

    def upload_events(self, event_dir: str, api_url: str, camera_name: str, video_name:str, algorithm_id: str):
        """上传事件包"""
        result = {
            "total": 0,
            "success": 0,
            "failed": []
        }

        for event_folder in Path(event_dir).glob("event_*"):
            if not event_folder.is_dir():
                continue

            result["total"] += 1
            try:
                # 获取事件文件
                key_files = sorted(event_folder.glob("key_*.jpg"))
                print("key_files: ",key_files)

                gif_file = next(event_folder.glob("*.gif"), None)

                print("key_files: ",gif_file)

                time_str = datetime.fromisoformat(
                    (event_folder / "timestamp").read_text()
                ).strftime("%Y-%m-%d %H:%M:%S")

                # 构建请求体
                fields = {
                    "cameraName": camera_name,
                    "videoName":  video_name,
                    "algorithmId": algorithm_id,
                    "occurTime": time_str,
                    "firstImg": ("first.jpg", open(key_files[0], "rb"), "image/jpeg"),
                    "img": ("middle.jpg", open(key_files[1], "rb"), "image/jpeg"),
                    "lastImg": ("last.jpg", open(key_files[2], "rb"), "image/jpeg")
                }

                # 添加GIF文件
                if gif_file and gif_file.exists():
                    fields["video"] = (gif_file.name, open(gif_file, "rb"), "image/gif")

                # 发送请求
                encoder = MultipartEncoder(fields=fields)
                response = requests.post(
                    api_url,
                    data=encoder,
                    headers={"Content-Type": encoder.content_type},
                    timeout=30
                )

                if response.ok:
                    result["success"] += 1
                else:
                    result["failed"].append(event_folder.name)

            except Exception as e:
                result["failed"].append(event_folder.name)
                print(f"上传失败 {event_folder.name}: {str(e)}")
            finally:
                # 确保关闭所有文件
                for field in fields.values():
                    if isinstance(field, tuple):
                        field[1].close()

        return result


import time


# 使用示例
if __name__ == "__main__":
    uploader = EventUploader()
    
    # 生成事件包
    start_time = time.time()
    events = "/data/control_communication/chunk_0001/chunk_0001_mp4/problem_cross"
    
    uploader.generate_events(
        source_dir=events,
        output_dir=events
    )
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f"经过的时间: {elapsed_time} 秒")
    

    # 上传事件
    # report = uploader.upload_events(
    #     event_dir = events,
    #     api_url="http://192.168.0.142:80/aiApi/saveEvent",
    #     camera_name="chunk_0000",
    #     video_name = "chunk_0000",
    #     algorithm_id="2"
    # )
    
    # print(f"成功上传: {report['success']}/{report['total']}")